package com.jd.basic.utils;

import com.jd.basic.enm.JwtRasHolder;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.jwt.UserInfo;
import com.jd.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * @author 小林同学
 * @version 1.0
 * @description: TODO
 * @date 2023/3/13 16:44
 */
public class LoginContext {
    public static UserInfo getUserInfo(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        // 获取公钥
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(JwtRasHolder.INSTANCE.getJwtRasPubData()).getFile());
        // 通过token获取载荷
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
        if (null == payload || null == payload.getUserInfo()){
            return null;
        }
        return payload.getUserInfo();
    }

    public static UserInfo getUserInfo(){
        return ThreadLocalUtil.getThreadLocal();
    }
    public static Logininfo getLoginInfo(){
        return ThreadLocalUtil.getThreadLocal().getLogininfo();
    }
}
